//////////////////////////////////////////////////////////////////////////////////////////
// NAME: ViewLog.java								            						//
// AUTHOR: CDT Peter Lofreddo															//
// LAST MODIFIED: 27 February 2012														//
// DESCRIPTION: Contains methods for File IO for Nullwall 								//
// LIMITATIONS: 																		//
// CITATIONS: Inside Individual Methods.												//
//																						//
////////////////////////////////////////////////////////////////////////////////////////// 
package com.IPR2.viewlog;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.List;

import android.app.Activity;
import android.app.ActivityManager;
import android.app.ActivityManager.RunningAppProcessInfo;
import android.content.Intent;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.util.Log;
import android.widget.TextView;



public class ViewLog extends Activity {
	private TextView tv;

	/** Called when the activity is first created. */
	
	
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.main);
		tv = (TextView) findViewById(R.id.TextView01);

		InitializeNullwall();
	
	}
	
	public void InitializeNullwall()
	//////////////////////////////////////////////////////////////////////////////////////////
	//NAME: InitializeNullwall()															//
	//AUTHOR: CDT Peter Lofreddo 															//
	//LAST MODIFIED: 27 February 2012 														//
	//DESCRIPTION: Initializes Catalog System.  											//
	//LIMITATIONS: 																			//
	//CITATIONS: 																			//
	//																						//
	//////////////////////////////////////////////////////////////////////////////////////////
	{
		String TAG = "InitializeNullwall";
		//Creates a directory to look for files
		File root = new File(Environment.getExternalStorageDirectory(),
		"Nullwall");
		File file = new File(root, "black.txt");
		File file2 = new File(root, "white.txt");
		File file3 = new File(root, "installed_programs.txt");
		File file4 = new File(root, "active_processes.txt");
		
		
		
if (!file.exists()) {
	CreateFile("black.txt");
	Log.d(TAG,"black.txt not found. Creating file...");
	}

if (!file2.exists()) {
	CreateFile("white.txt");
	Log.d(TAG,"white.txt not found. Creating file...");
	}

if (!file3.exists()) {
	CreateFile("installed_programs.txt");
	Log.d(TAG,"installed_programs.txt not found. Creating file...");
	}

if (!file4.exists()) {
	CreateFile("active_processes.txt");
	Log.d(TAG,"active_processes.txt not found. Creating file...");
	}

	}
	
	public void RemoveStrFromFile(String blackorwhite, String packageName)
	//////////////////////////////////////////////////////////////////////////////////////////
	//NAME: DoWork(String deleteFromFile) 													//
	//AUTHOR: CDT Peter Lofreddo 															//
	//LAST MODIFIED: 27 February 2012 														//
	//DESCRIPTION: Deletes a String from a file												//
	//LIMITATIONS: Search Queries cast to lowercase for ease of use.						//
	//CITATIONS: Adapted from http://stackoverflow.com/questions/1377279/					//
	//java-find-a-line-in-a-file-and-remove													//
	//																						//
	//////////////////////////////////////////////////////////////////////////////////////////
//assumes black_list.txt or white_list.txt is 
//already created in mnt/sdcard/Nullwall directory
{

try{
//Makes sure programmer uses black or white as argument for method.
if (!blackorwhite.equalsIgnoreCase("black"))
{
if (!blackorwhite.equalsIgnoreCase("white"))
{
	Log.e("FileOp_RemoveStrFromFile","RemoveStrFromList() must have white or black as an argument");
}
}

//locates a black_list.txt or white_list.txt in Nullwall Directory
File root = new File(Environment.getExternalStorageDirectory(),"Nullwall");
File file = new File(root, blackorwhite +  ".txt");
File temp = new File(root,"temp.txt");

//creates buffers
BufferedReader bufferedReader = new BufferedReader(new FileReader(file.getAbsolutePath()));
PrintWriter printerWriter = new PrintWriter(new FileWriter(temp.getAbsolutePath()));


String line = null; 
//Read from the original file and write to the new 
//unless content matches data to be removed. 
while ((line = bufferedReader.readLine()) != null) { 
if (!line.trim().equalsIgnoreCase(packageName)) { 
printerWriter.println(line + "\r\n"); 
printerWriter.flush(); 
} 
} 
printerWriter.close(); 
bufferedReader.close(); 

//Delete the original file 
if (!file.delete()) { 
System.out.println("Could not delete file, error RemoveFromList()");
return; 
} 

//Rename the new file to the filename the original file had. 
if (!temp.renameTo(file)) 
System.out.println("Could not rename file, error RemoveFromList()"); 

} 
catch (FileNotFoundException ex) { 
ex.printStackTrace(); 
Log.e("FileOp_RemoveStrFromFile","RemoveStrFromList() File Not Found!");

} 
catch (IOException ex) { 
ex.printStackTrace(); 
Log.e("FileOp_RemoveStrFromFile","RemoveStrFromList() IOException!");
} 

}
			      
	public void UninstallApplication(String packageName)
		//////////////////////////////////////////////////////////////////////////////////////////
		// NAME: UninstallApplication(String packageName)					           			//
		// AUTHOR: CDT Peter Lofreddo															//
		// LAST MODIFIED: 02 February 2012														//
		// DESCRIPTION:Uninstalls Package Permanently from Android.					 			//
		// LIMITATIONS:	Must still ask user to permanently uninstall.							//
		// CITATIONS:Adapted from http://android.amberfog.com/?p=98								//
		// 																						//
		////////////////////////////////////////////////////////////////////////////////////////// 
	{
		Uri packageURI = Uri.parse("package:"+packageName);
		Intent uninstallIntent = new Intent(Intent.ACTION_DELETE, packageURI);
		startActivity(uninstallIntent);
	}
		     	      	
	public void ListAllActivePrograms()
	//////////////////////////////////////////////////////////////////////////////////////////
	// NAME: ListAllActivePrograms()					            						//
	// AUTHOR: CDT Peter Lofreddo															//
	// LAST MODIFIED: 23 February 2012														//
	// DESCRIPTION: Lists package names active on Android Device					 		//
	// LIMITATIONS: 																		//
	// CITATIONS:adapted from http://www.dreamincode.net/forums/topic/						//			//
	// 138412-android-20-list-of-running-applications/										//
	//																						//
	//////////////////////////////////////////////////////////////////////////////////////////
	{
//		TextView tv = new TextView(this);
//		        this.setContentView(tv);
		PackageManager pm = getPackageManager(); 
		List<ApplicationInfo> packages = pm 
        .getInstalledApplications(PackageManager.GET_META_DATA);
		ActivityManager actvityManager = (ActivityManager)
	     
	    this.getSystemService( ACTIVITY_SERVICE );
		List<RunningAppProcessInfo> procInfos = actvityManager.getRunningAppProcesses();
				tv.append("\n");
		for(int i = 0; i < procInfos.size(); i++)
		     {
					//AppendFile(procInfos.get(i).processName, "activepackages.txt");
			    tv.setText(tv.getText().toString()+procInfos.get(i).processName+ "\r\n"); 
			}		     
	}
	
	public void ListAllInstalledPrograms()
		//////////////////////////////////////////////////////////////////////////////////////////
		// NAME: ListAllInstalledPrograms()					            						//
		// AUTHOR: CDT Peter Lofreddo															//
		// LAST MODIFIED: 26 February 2012														//
		// DESCRIPTION: Lists package names installed on Android Device					 		//
		// LIMITATIONS: Only Shows Apps installed by user. No System Apps (phone, mms, etc.)	//
		// CITATIONS:http://stackoverflow.com/questions/2695746/								//
		// how-to-get-a-list-of-installed-android-applications-and-pick-one-to-run 				//
		// http://stackoverflow.com/questions/2695746/											//
		// how-to-get-a-list-of-installed-android-applications-and-pick-one-to-run				//
		//																						//
		////////////////////////////////////////////////////////////////////////////////////////// 
	{
		final PackageManager pm = getPackageManager(); 
		
		        //get a list of installed app objects. 
		        List<ApplicationInfo> packages = pm 
		                .getInstalledApplications(PackageManager.GET_META_DATA); 
		        
		        tv.append("\n");        
		        for (ApplicationInfo packageInfo : packages) 
		        { 
		        	if ((packageInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0)
		        	{
		        		//System Package, Not showing
		        		//tv.append("System Package!" + "\n");
		        	}
		        	else {
		        		//Not a System Package. Showing.
		        		try{
		        			//Gives PackageNames instead of Simple Names
			        		//tv.append(packageInfo.packageName + "\n");
		        			
		        			
		        			//Gives Simple Names of Packages
		        		CharSequence c = pm.getApplicationLabel(pm.getApplicationInfo(packageInfo.packageName, PackageManager.GET_META_DATA));
		        		tv.append(c.toString()+ "\n");
		        		   }
		        		catch(Exception e){
		        			Log.e("ListAllInstalledPrograms()","Name Not Found Exception");
		        		}
		        		
		        	}
			                		
		        }
    } 

	public void checkExternalMedia() {
		//////////////////////////////////////////////////////////////////////////////////////////
		// NAME: checkExternalMedia() 															//
		// AUTHOR: CDT Peter Lofreddo 															//
		// LAST MODIFIED: 13 February 2012 														//
		// DESCRIPTION: Determines whether external media is available and						//
		// writable.  Useful for making sure USB Storage Mode is disabled and file can be		//
		// written.																				//
		// CITATIONS: Adapted from http://eagle.phys.utk.edu/guidry/android/writeSD.html 		//
		// 																						//
		// ///////////////////////////////////////////////////////////////////////////////////////
		boolean mExternalStorageAvailable = false;
		boolean mExternalStorageWriteable = false;
		String state = Environment.getExternalStorageState();

		if (Environment.MEDIA_MOUNTED.equals(state)) {
			// Can read and write the media
			mExternalStorageAvailable = mExternalStorageWriteable = true;
		} else if (Environment.MEDIA_MOUNTED_READ_ONLY.equals(state)) {
			// Can only read the media
			mExternalStorageAvailable = true;
			mExternalStorageWriteable = false;
		} else {
			// Can't read or write
			mExternalStorageAvailable = mExternalStorageWriteable = false;
		}
		Log.d("Testing_checkExternalMedia","\n\nExternal Media: readable=" + mExternalStorageAvailable
				+ " writable=" + mExternalStorageWriteable);
	}

	public void ReadLocalResourceFile() {
		//////////////////////////////////////////////////////////////////////////////////////////
		// NAME: ReadFileFromResRaw() 															//
		// AUTHOR: CDT Peter Lofreddo 															//
		// LAST MODIFIED: 29 January 2012 														//
		// DESCRIPTION: Reads a file from Res/Raw directory of application.						//
		// Directory is READONLY 																//
		// LIMITATIONS: Does not read all files on the filesystem. 								//
		// CITATIONS: Adapted from																//
		// http://eagle.phys.utk.edu/guidry/android/writeSD.html 								//
		// 																						//
		//////////////////////////////////////////////////////////////////////////////////////////
		tv.append("\nData read from res/raw/textfile.txt:");
		InputStream is = this.getResources().openRawResource(R.raw.textfile);
		InputStreamReader isr = new InputStreamReader(is);
		BufferedReader br = new BufferedReader(new InputStreamReader(this
				.getResources().openRawResource(R.raw.textfile)), 8192); 
		try {
			String test;
			while (true) {
				test = br.readLine();
				// readLine() returns null if no more lines in the file
				if (test == null)
					break;
				tv.append("\n" + "    " + test);
			}
			isr.close();
			is.close();
			br.close();
		} catch (IOException e) {
			e.printStackTrace();
		}
		tv.append("\n\n EOF");
	}

	public void CreateFile(String fileName)
	//////////////////////////////////////////////////////////////////////////////////////////
	// NAME: CreateFile(String fileName)													//
	// AUTHOR: CDT Peter Lofreddo 															//
	// LAST MODIFIED: 27 February 2012 														//
	// DESCRIPTION: Creates a blank file in the Nullwall directory.							//
	// 																						//
	// AppendLogFile(String sBody). It has been added to provide clarity an					//
	// intuitive codebase 																	//
	// does not need CreateLogFile() to first append to file; Used for clarity				//
	// 																						//
	// CITATIONS: Adapted from http://stackoverflow.com/questions/4580683/ 					//
	// android-java-writing-text-file-to-sd-card 											//
	// 																						//
	//////////////////////////////////////////////////////////////////////////////////////////
{
	try {
		File root = new File(Environment.getExternalStorageDirectory(),
				"Nullwall");
		if (!root.exists()) {
			root.mkdirs();
		}
		Log.d("FileOp_CreateFile","File Created in Directory" + root);
		File gpxfile = new File(root, fileName);
		FileWriter writer = new FileWriter(gpxfile, true);
		writer.write("");
		writer.flush();
		writer.close();
		Log.d("FileOp_CreateFile",fileName + " Successfully Created!");
	} catch (IOException e) {
		Log.d("FileOp_CreateFile",fileName + " not Saved! CreateFile() Broken!");
	}
}

	public void AppendFile(String sBody, String fileName) {
		//////////////////////////////////////////////////////////////////////////////////////////
		// NAME: AppendFile(String sBody, String fileName) 										//
		// AUTHOR: CDT Peter Lofreddo 															//
		// LAST MODIFIED: 13 February 2012 														//
		// DESCRIPTION: Adds text to a file located in the Nullwall Directory					//
		// does not need CreateLogFile() to first append to file; Used for clarity				//
		// CITATIONS: Adapted from http://stackoverflow.com/questions/4580683/					//
		// android-java-writing-text-file-to-sd-card 											//
		// 																						//
		//////////////////////////////////////////////////////////////////////////////////////////
		try {
			File root = new File(Environment.getExternalStorageDirectory(),
					"Nullwall");
			if (!root.exists()) {
				root.mkdirs();
			}
			Log.d("FileOp_AppendFile", "Log File Created In Directory: " + root);
			File gpxfile = new File(root, fileName);
			FileWriter writer = new FileWriter(gpxfile, true);
			writer.write(sBody.toLowerCase() + "\r\n");
			writer.flush();
			writer.close();
			Log.d("FileOp_AppendFile", fileName + " File Successfully Appended!");
		} catch (IOException e) {
			Log.d("FileOp_AppendFile", fileName + " not Saved! AppendFile() Broken!");
		}
	}

	public void ReadFileTextView(String fileName) {
		//////////////////////////////////////////////////////////////////////////////////////////
		// NAME: ReadFile(String fileName) 														//
		// AUTHOR: CDT Peter Lofreddo 															//
		// LAST MODIFIED: 12 February 2012 														//
		// DESCRIPTION: Reads a file from mnt/sdcard/Nullwall_Logfiles, displays using textView	//
		// CITATIONS: Adapted from http://www.anddev.org/read_a_txt_file_ 						//
		// from_sd_card_in_a_real_device-t6619.html 											//
		// 																						//
		//////////////////////////////////////////////////////////////////////////////////////////
		try {
			File f = new File(Environment.getExternalStorageDirectory()
					+ "/Nullwall/" + fileName);
			FileInputStream fileIS = new FileInputStream(f);
			BufferedReader buf = new BufferedReader(new InputStreamReader(
					fileIS));
			String readString = new String();
			Log.d("FileOp_ReadFile","Reading File...");

			// just reading each line and pass it on the debugger
			while ((readString = buf.readLine()) != null) {
				tv.append(readString);
				tv.append("\r\n");
			}

		} catch (FileNotFoundException e) {
			Log.e("FileOp_ReadFile","File Not Found");
			e.printStackTrace();

		} catch (IOException e) {
	 		Log.e("FileOp_ReadFile","IOException! ReadFile() Broken!");
			e.printStackTrace();

		}
	}

	public void ClearFile(String fileName) {
		//////////////////////////////////////////////////////////////////////////////////////////
		// NAME: ClearFile(String fileName)														//
		// AUTHOR: CDT Peter Lofreddo 															//
		// LAST MODIFIED: 13 February 2012 														//
		// DESCRIPTION: Clears a file located in Nullwall Directory. Does not Delete File.		//
		// CITATIONS: N/A																		//
		// 																						//
		//////////////////////////////////////////////////////////////////////////////////////////
		try {
			File root = new File(Environment.getExternalStorageDirectory(),
					"Nullwall");
			if (!root.exists()) {
				root.mkdirs();
			}
			File gpxfile = new File(root, fileName);
			FileWriter writer = new FileWriter(gpxfile, false);
			writer.write("");
			writer.flush();
			writer.close();
		} catch (FileNotFoundException e) {
			Log.e("FileOp_ClearFile","File not Found! ClearLog() Broken!");
			e.printStackTrace();

		} catch (IOException e) {
			Log.e("FileOp_ClearFile", "IOException! ClearLog() Broken!");
			e.printStackTrace();
		}
	}
	
	public void DeleteFile(String fileName)
	//////////////////////////////////////////////////////////////////////////////////////////
	//NAME: DeleteFile(String fileName) 													//
	//AUTHOR: CDT Peter Lofreddo 															//
	//LAST MODIFIED: 13 February 2012 														//
	//DESCRIPTION: Deletes a file in the Nullwall Directory									//
	//LIMITATIONS: Must be in Nullwall Directory											//
	//																						//
	//////////////////////////////////////////////////////////////////////////////////////////
{
	File root = new File(Environment.getExternalStorageDirectory(),"Nullwall");
	File file = new File(root, fileName);
	if (!file.delete())
	{
		Log.e("FileOp_DeleteFile",fileName + " could not be deleted");	
	}
}
	
	public boolean SearchFile(String searchString,String fileName, Boolean caseSensitive) {
		//////////////////////////////////////////////////////////////////////////////////////////
		// NAME: SearchFile(String searchString,String fileName, Boolean caseSensitive)			//
		// AUTHOR: CDT Peter Lofreddo															//
		// LAST MODIFIED: 13 February 2012 														//
		// DESCRIPTION: Searches in file for string in Nullwall Directory. 						//
		// caseSensitive = true for Case sensitive 												//
		// searching, choose false to ignore case 												//
		// CITATIONS: Adapted																	//
		// From http://stackoverflow.com/questions/5912753/java-find-and-replace-text			//
		// 																						//
		//////////////////////////////////////////////////////////////////////////////////////////
		boolean found = false;
		try {
			File f = new File(Environment.getExternalStorageDirectory()
					+ "/Nullwall/" + fileName);
			FileInputStream fileIS = new FileInputStream(f);
			BufferedReader buf = new BufferedReader(new InputStreamReader(
					fileIS));
			String line;
			while ((line = buf.readLine()) != null) {
				line = buf.readLine();
				if (caseSensitive) {
					if (line.equals(searchString)) {
						found = true;
						Log.d("FileOp_SearchFile","File Found! Case Sensitive");
					}
				} else if (line.equalsIgnoreCase(searchString)) {
					found = true;
					Log.d("FileOp_SearchFile","File Found! Not Case Sensitive");
				}
			}
			if (found) {
				Log.e("FileOp_SearchFile","You did not find " + searchString
						+ " in the log file");
			}
			return found;
		} catch (FileNotFoundException e) {
			Log.e("FileOp_SearchFile","File not Found! SearchFile() Broken!");
			e.printStackTrace();
			return true;

		} catch (IOException e) {
			Log.e("FileOp_SearchFile","IOException! SearchFile() Broken!");
			e.printStackTrace();
			return true;
		}
	}
}
